import 'dart:convert';
import 'dart:io';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:insta_image_viewer/insta_image_viewer.dart';
import 'package:school_assistant/toast_utils.dart';
import 'package:school_assistant/user_feedback_imgs.dart';
import 'package:sp_util/sp_util.dart';

import 'common_client.dart';
import 'data/article_entity.dart';
import 'data/article_extra_entity.dart';
import 'data/base_data_entity.dart';

class PostPage extends StatefulWidget {
  const PostPage({Key? key}) : super(key: key);

  @override
  State<PostPage> createState() => _PostPageState();
}

class _PostPageState extends State<PostPage> {
  List<XFile> imgFeed = [];
  final _controllerTitle = TextEditingController();
  final _controllerContent = TextEditingController();
  final _controllerPhone = TextEditingController();
  final _controllerAddress = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _controllerTitle.dispose();
    _controllerContent.dispose();
    _controllerPhone.dispose();
    _controllerAddress.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff5f5f5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Get.back(),
          icon: Icon(
            Icons.arrow_back_ios,
            color: Colors.black,
          ),
        ),
        centerTitle: true,
        title: Text(
          "我要发布",
          style: TextStyle(
              fontSize: 18, color: Colors.black, fontWeight: FontWeight.w600),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Flexible(
              child: Container(
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(4)),
            margin: EdgeInsets.all(12),
            padding: EdgeInsets.all(12),
            child: ListView(
              children: [
                Text(
                  "标题",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                TextField(
                  maxLength: 30,
                  controller: _controllerTitle,
                  maxLines: 1,
                  decoration: InputDecoration(
                      hintText: '请输入标题',
                      filled: true,
                      border: InputBorder.none,
                      fillColor: Color(0XFFF1F1F1)),
                ),
                Text(
                  "正文",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                TextField(
                  maxLength: 140,
                  maxLines: 4,
                  controller: _controllerContent,
                  decoration: InputDecoration(
                      hintText: '请输入正文',
                      filled: true,
                      border: InputBorder.none,
                      fillColor: Color(0XFFF1F1F1)),
                ),
                // Text(
                //   "联系方式",
                //   style: TextStyle(color: Color(0xff333333), fontSize: 16),
                // ),
                // SizedBox(
                //   height: 8,
                // ),
                // TextField(
                //   maxLines: 1,
                //   maxLength: 13,
                //   controller: _controllerPhone,
                //   inputFormatters: [
                //     //限制只允许输入数字
                //     FilteringTextInputFormatter.digitsOnly,
                //     // //限制输入长度不超过11位
                //     LengthLimitingTextInputFormatter(11),
                //   ],
                //   keyboardType: TextInputType.number,
                //   decoration: InputDecoration(
                //       counterText: "",
                //       hintText: '请输入联系方式',
                //       filled: true,
                //       border: InputBorder.none,
                //       fillColor: Color(0XFFF1F1F1)),
                // ),
                // SizedBox(
                //   height: 10,
                // ),
                // Text(
                //   "联系地址",
                //   style: TextStyle(color: Color(0xff333333), fontSize: 16),
                // ),
                // SizedBox(
                //   height: 8,
                // ),
                // TextField(
                //   maxLines: 1,
                //   controller: _controllerAddress,
                //   decoration: InputDecoration(
                //       hintText: '请输入常驻的地址',
                //       filled: true,
                //       border: InputBorder.none,
                //       fillColor: Color(0XFFF1F1F1)),
                // ),
                SizedBox(
                  height: 8,
                ),
                Text(
                  "图片",
                  style: TextStyle(color: Color(0xff333333), fontSize: 16),
                ),
                SizedBox(
                  height: 8,
                ),
                GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 4,
                    childAspectRatio: 1,
                  ),
                  itemCount: imgFeed.length < 3 ? imgFeed.length + 1 : 3,
                  itemBuilder: (context, index) {
                    //   return Image.file(File(imgAD[index].path));
                    return index < imgFeed.length
                        ? _singleAD(index)
                        : _imgAdd(index);
                  },
                )
              ],
            ),
          )),
          GestureDetector(
            onTap: () {
              // print(DateTime.now().toLocal().toString().substring(0,19));
              _postArticle();
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(left: 12, right: 12, bottom: 10),
              height: 50,
              decoration: BoxDecoration(
                  color: Color(0xff83DF00),
                  borderRadius: BorderRadius.circular(4)),
              child: Text(
                "发布",
                style: TextStyle(
                    color: Color(0XFF333333),
                    fontSize: 18,
                    fontWeight: FontWeight.w600),
              ),
            ),
          )
        ],
      ),
    );
  }

  _postArticle() async {
    try {
      if (_controllerTitle.text.isEmpty) {
        return QmToast.toast('请输入标题!');
      }
      if (_controllerContent.text.isEmpty) {
        return QmToast.toast('请输入内容!');
      }
      // if (_controllerPhone.text.isEmpty) {
      //   return QmToast.toast('请输入联想方式!');
      // }
      // if (_controllerAddress.text.isEmpty) {
      //   return QmToast.toast('请输入常驻地址!');
      // }
      if (imgFeed.isEmpty) {
        return QmToast.toast('请至少传一张图!');
      }

      EasyLoading.show(status: 'loading...');
      List<String> urls = [];
      if (imgFeed.isNotEmpty) {
        for (var element in imgFeed) {
          await _uploadImg(element).then((value) => urls.add(value));
        }
      }
      var extra = ArticleExtraEntity();
      // extra.contract = _controllerPhone.text;
      // extra.loc = _controllerAddress.text;
      extra.username = SpUtil.getString("username");
      extra.profile = SpUtil.getString("profile");
      extra.sex = SpUtil.getInt("sex", defValue: 1);
      extra.time = DateTime.now().toLocal().toString().substring(0, 19);
      var res = await CommonClient().postArticle(SpUtil.getString("uid") ?? '',
          1, _controllerTitle.text, _controllerContent.text, jsonEncode(urls),
          extra: jsonEncode(extra));
      if (res.status == true) {
        Get.back(result: true);
      }
      print(res);
    } catch (e) {
      print(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  _singleAD(int pos) {
    return Stack(
      children: [
        Positioned(
          right: 6,
          top: 6,
          child: InstaImageViewer(
            child: Image.file(
              File(imgFeed[pos].path),
              width: 68,
              height: 68,
              fit: BoxFit.cover,
              alignment: Alignment.topCenter,
            ),
          ),
        ),
        Positioned(
          right: 0,
          child: GestureDetector(
              onTap: () {
                imgFeed.removeAt(pos);
                setState(() {});
              },
              child: Image.asset(
                UserFeedBackImgs.user_feedback_del,
                width: 18,
              )),
        )
      ],
    );
  }

  _imgAdd(int pos) {
    return Stack(
      children: [
        Positioned(
            right: 6,
            top: 6,
            left: 5,
            bottom: 5,
            child: GestureDetector(
              onTap: () => getLostData(pos),
              child: DottedBorder(
                color: Color(0xffE3E3E3),
                strokeWidth: 1,
                radius: const Radius.circular(4),
                child: Center(
                  child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(children: [
                        WidgetSpan(
                            child: Image.asset(
                          UserFeedBackImgs.user_feedback_camare,
                          width: 14,
                        )),
                        const TextSpan(
                          text: '\n',
                        ),
                        TextSpan(
                            text: "上传图片",
                            style: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 9,
                                height: 2))
                      ])),
                ),
              ),
            ))
      ],
    );
  }

  Future<String> _uploadImg(XFile locFile) async {
    var file = File(locFile.path);
    BaseDataEntity model = await CommonClient().commonUpFile(file);
    if (model.status == true) {
      return model.data ?? '';
    } else {
      return '';
    }
  }

  getLostData(int pos) async {
    if (imgFeed.length >= 3) {
      QmToast.toast("最多选3张图片");
      return;
    }
    final ImagePicker picker = ImagePicker();
    final XFile? image =
        await picker.pickImage(source: ImageSource.gallery, imageQuality: 70);
    if (image != null) imgFeed.insert(pos, image);
    setState(() {});
  }
}
